//
//  NSString+MD5.m
//  AccountEasy
//
//  Created by mac on 2020/7/27.
//  Copyright © 2020 AccountEasy. All rights reserved.
//

#import "NSString+MD5.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

@implementation NSString (MD5)

+ (NSString *)stringToMD5:(NSString *)str {

    if(str == nil || [str length] == 0)
        return nil;
    
    const char *value = [str UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    
    return outputString;
}

+ (NSString *)getHmacmd5:(NSString *)clearText withSecret:(NSString *)secret
{
   CCHmacContext ctx;
  //使用GBK编码
  unsigned long encode =   CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

  const char *key = [secret cStringUsingEncoding:encode];
  const char *str = [clearText cStringUsingEncoding:encode];
  unsigned char mac[CC_MD5_DIGEST_LENGTH];
  char hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
  char *p;
  CCHmacInit(&ctx, kCCHmacAlgMD5, key, strlen(key));
  CCHmacUpdate(&ctx, str, strlen(str));
  CCHmacFinal(&ctx, mac);
  p = hexmac;
  for (int i = 0; i < CC_MD5_DIGEST_LENGTH;i++) {
      snprintf(p,3,"%02x", mac[ i ]);
      p += 2;
  }
  return [NSString stringWithCString:hexmac encoding:encode];
}

+ (NSString *)getMD5WithData:(NSData *)data {
    //1: 创建一个MD5对象
    CC_MD5_CTX md5;
    //2: 初始化MD5
    CC_MD5_Init(&md5);
    //3: 准备MD5加密
    CC_MD5_Update(&md5, data.bytes, (uint32_t)data.length);
    //4: 准备一个字符串数组, 存储MD5加密之后的数据
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    //5: 结束MD5加密
    CC_MD5_Final(result, &md5);
    NSMutableString *resultString = [NSMutableString string];
    //6:从result数组中获取最终结果
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
      [resultString appendFormat:@"%02x", result[i]];
    }
    return resultString;
}

@end
